package com.fencing_squad.homo.page;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.list.Post;
import com.fencing_squad.homo.list.PostProvider;
import com.fencing_squad.homo.util.CustomComponent;
import com.fencing_squad.homo.util.Data;
import com.fencing_squad.homo.util.Network;
import com.fencing_squad.homo.util.function.FunctionInt;
import com.fencing_squad.homo.util.function.FunctionObject;
import com.fencing_squad.homo.util.function.FunctionVoid;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Community {
    private PostProvider postProvider = null;
    private Component community = null;
    private Context context = null;
    private String postText = "";
    private CommonDialog window = null;
    private byte[] img = null;
    FunctionVoid redirectToLogin = null;
    private CommonDialog tip = null;

    public Component get(Context context, FunctionObject checkItem, FunctionInt selectImg, FunctionVoid redirectToLogin) {
        if(community == null) {
            community = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_community, null, false);
        }
        this.redirectToLogin = redirectToLogin;
        this.context = context;
        Component post = community.findComponentById(ResourceTable.Id_post);
        ListContainer listContainer = (ListContainer) community.findComponentById(ResourceTable.Id_postList);
        postProvider = new PostProvider(community.getContext());
        listContainer.setItemProvider(postProvider);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                if (i == 0) {
                    checkItem.func(null);
                }
                else {
                    checkItem.func(postProvider.getItem(i));
                }
            }
        });

        listContainer.addScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int x, int y, int oldX, int oldY) {
                System.out.println("scroll");
                System.out.println(component instanceof ListContainer);
                System.out.println(y);
            }
        });

        Community self = this;

        post.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(!Data.Account.isLogin) {
                    redirectToLogin.func();
                    return;
                }
                window = CustomComponent.getNewPost(context, self::textChange, selectImg, self::submit, null);
                window.show();
            }
        });
        refresh();
        return community;
    }

    private void textChange(String text) {
        postText = text;
    }

    public void refresh() {
        Map<String, String> params = new ConcurrentHashMap<>();
        if (postProvider != null && postProvider.getSize() > 0) {
            params.put("new_time", String.valueOf(postProvider.getList().get(0).getTimestamp()));
        }
        params.put("by", "refresh");
        Network.get("/post", params, this::getPostRefresh, this::reject);
    }

    public void next() {
        Map<String, String> params = new ConcurrentHashMap<>();
        if (postProvider != null && postProvider.getSize() > 0) {
            params.put("old_time", String.valueOf(postProvider.getList().get(postProvider.getSize() - 1).getTimestamp()));
        }
        params.put("by", "next");
        Network.get("/post", params, this::getPostNext, this::reject);
    }

    private void submit() {
        JSONObject object = new JSONObject();
        object.put("content", postText);
        if(img != null) {
            System.out.println("img send");
            JSONArray array = new JSONArray();
            array.add(Base64.getEncoder().encodeToString(img));
            object.put("image_streams", array);
        }
        System.out.println(object);
        Network.postJson("/post", object.toJSONString(), this::postResolve, this::reject);
    }

    public void getPostNext(JSONObject object) {
        List<Post> posts = Post.getFromJSONArray(object.getJSONArray("data"));
        if (posts != null) {
            postProvider.append(posts);
        }
    }

    public void getPostRefresh(JSONObject object) {
        System.out.println(object);
        List<Post> posts = Post.getFromJSONArray(object.getJSONArray("data"));
        if (posts != null) {
            postProvider.prepend(posts);
        }
    }

    public void postResolve(JSONObject object) {
        CustomComponent.getToastDialog(context, "发送成功").show();
        if (window != null) {
            window.hide();
        }
    }

    public void reject(int code, String err) {
        if (code == 404) {
            tip = CustomComponent.getDialog(context, err, () -> {
                if (tip != null) {
                    tip.hide();
                }
            }, () -> {
                if (tip != null) {
                    tip.hide();
                }
            });
            tip.show();
        }
        else {
            System.out.println("my err " + err);
        }
    }

    public void setImageURI(String value) {
        //定义数据能力帮助对象
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        //定义图片来源对象
        ImageSource imageSource = null;
        //获取选择的Img对应的Id
        String chooseImgId = null;
        //如果是选择文件则getUriString结果为content://com.android.providers.media.documents/document/image%3A30，其中%3A是":"的URL编码结果，后面的数字就是image对应的Id
        //如果选择的是图库则getUriString结果为content://media/external/images/media/30，最后就是image对应的Id
        //这里需要判断是选择了文件还是图库
        if(value.lastIndexOf("%3A")!=-1){
            chooseImgId = value.substring(value.lastIndexOf("%3A")+3);
        }
        else {
            chooseImgId = value.substring(value.lastIndexOf('/')+1);
        }
        //获取图片对应的uri，由于获取到的前缀是content，我们替换成对应的dataability前缀
        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,chooseImgId);
        try {
            //读取图片
            FileDescriptor fd = helper.openFile(uri, "r");
            imageSource = ImageSource.create(fd, null);
            //创建位图
            PixelMap pixelMap = imageSource.createPixelmap(null);

            CustomComponent.addImage(window, pixelMap);

            InputStream in = helper.obtainInputStream(uri);
            img = new byte[in.available()];
            System.out.println(in.available());
            in.read(img);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (imageSource != null) {
                imageSource.release();
            }
        }
    }

//    public void test1() {
//        Post post = new Post();
//        post.setContent("contentttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt" + String.valueOf(2));
//        post.setComment(114);
//        post.setLikes(514);
//        post.setNickname("nick" + String.valueOf(1919));
//        System.out.println("testaaaaa");
//        postProvider.append(post);
//    }

    public static ArrayList<Post> test() {
        ArrayList<Post> list = new ArrayList<>();
        for(int i=0; i<1; i++) {
            Post post = new Post();
            post.setContent("contentttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt" + String.valueOf(i));
            post.setComment(i);
            post.setLikes(i);
            post.setNickname("nick" + String.valueOf(i));
            list.add(post);
        }
        return list;
    }
}
